package labox.innovation.status;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javolution.util.FastList;
import labox.innovation.config.Config;
import labox.innovation.config.Server;
import labox.innovation.util.Rnd;

public class Status extends Thread {
	
	protected static final Logger _log = LoggerFactory.getLogger(Status.class.getName());

	private ServerSocket statusServerSocket;

	private int _uptime;

	private int _statusPort;

	private String _statusPw;

	private int _mode;

	private List<LoginStatusThread> _loginStatus;

	@Override
	public void run() {

		while (true) {
			try {
				Socket connection = statusServerSocket.accept();

				if (_mode == Server.MODE_GAMESERVER) {
					new GameStatusThread(connection, _uptime, _statusPw);
				} else if (_mode == Server.MODE_LOGINSERVER) {
					LoginStatusThread lst = new LoginStatusThread(connection, _uptime, _statusPw);
					if (lst.isAlive()) {
						_loginStatus.add(lst);
					}
				}
				if (this.isInterrupted()) {
					try {
						statusServerSocket.close();
					} catch (IOException io) {
						io.printStackTrace();
					}
					break;
				}
			} catch (IOException e) {
				if (this.isInterrupted()) {
					try {
						statusServerSocket.close();
					} catch (IOException io) {
						io.printStackTrace();
					}
					break;
				}
			}
		}
	}

	public Status(int mode) throws IOException {
		super("Status");
		_mode = mode;
		Properties telnetSettings = new Properties();
		InputStream is = new FileInputStream(new File(Config.TELNET_FILE));
		telnetSettings.load(is);
		is.close();

		if(_mode == Server.MODE_GAMESERVER)
			_statusPort = Integer.parseInt(telnetSettings.getProperty("GameServerStatusPort", "12345"));
		else
			_statusPort = Integer.parseInt(telnetSettings.getProperty("LoginServerStatusPort", "23456"));
		_statusPw = telnetSettings.getProperty("StatusPW");

		if (_mode == Server.MODE_GAMESERVER || _mode == Server.MODE_LOGINSERVER) {
			if (_statusPw == null) {
				_log.info("Server's Telnet Function Has No Password Defined!",Config.SERVER_ID,"telnet密码未定义");
				_log.info("A Password Has Been Automaticly Created!",Config.SERVER_ID,"telnet密码初始化");
				_statusPw = rndPW(10);
				_log.info("Password Has Been Set To: " + _statusPw,Config.SERVER_ID,"telnet密码");
			}
			_log.info("Telnet StatusServer started successfully, listening on Port: " + _statusPort,Config.SERVER_ID,"telnet开启成功");
		}
		statusServerSocket = new ServerSocket(_statusPort);
		_uptime = (int) System.currentTimeMillis();
		_loginStatus = new FastList<LoginStatusThread>();
	}

	/**
	 * 根据给定的长度生成一个随机的登陆密码
	 * 
	 * @param length
	 * @return
	 */
	private String rndPW(int length) {
		final String lowerChar = "qwertyuiopasdfghjklzxcvbnm";
		final String upperChar = "QWERTYUIOPASDFGHJKLZXCVBNM";
		final String digits = "1234567890";
		final StringBuilder password = new StringBuilder(length);

		for (int i = 0; i < length; i++) {
			int charSet = Rnd.nextInt(3);
			switch (charSet) {
			case 0:
				password.append(lowerChar.charAt(Rnd.nextInt(lowerChar.length() - 1)));
				break;
			case 1:
				password.append(upperChar.charAt(Rnd.nextInt(upperChar.length() - 1)));
				break;
			case 2:
				password.append(digits.charAt(Rnd.nextInt(digits.length() - 1)));
				break;
			}
		}
		return password.toString();
	}

	public void sendMessageToTelnets(String msg) {
		List<LoginStatusThread> lsToRemove = new FastList<LoginStatusThread>();
		for (LoginStatusThread ls : _loginStatus) {
			if (ls.isInterrupted()) {
				lsToRemove.add(ls);
			} else {
				ls.printToTelnet(msg);
			}
		}
	}
}
